package huu.eventLoop;

/**
 * @author huu
 * @create 2025-08-28-15:02
 */
public class ScheduleTask implements Runnable, Comparable<ScheduleTask>{

    private final Runnable task;
    //维护一个时间，实现比较
    private long deadline;
    //维护一个周期
    private long period;
    //维护一个事件循环
    private EventLoop eventLoop;

    public ScheduleTask(Runnable task, EventLoop eventLoop, long deadline, long period){
        this.task = task;
        this.deadline = deadline;
        this.period = period;
        this.eventLoop = eventLoop;
    }

    @Override
    public void run() {
        try{
            task.run();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            //再丢回定时任务队列
            if(period > 0){
                this.deadline += period;
                eventLoop.getScheduleTaskQueue().offer(this);
            }

        }

    }

    public long getDeadline(){
        return deadline;
    }

    @Override
    public int compareTo(ScheduleTask scheduleTask) {
        return (int)(this.deadline - scheduleTask.deadline);
    }
}
